const userUtils = require("../../utils/user");
const validate = require('../../utils/validate')
const common = require('../../utils/common')
const { getHomeData } = require('../../services/home')
const { updateBusinessTime } = require('../../services/stores')
const defaultHomeData = {
  shopVo: {
    address: '淄博市张店区联通路128号',
    shopName: '百花园超市',
    businessTime: '09:00~21:00',
    totalAmount: 0,
    daySumIncomeAmount: 0,
    sumIncomeAmount: 0,
    dayCount: 0,
    shopRank: 0,
    codeUrl: '../../images/home_qrcode.jpg',
  }
}
Page({
  data: {
    isLogin: false,
    minPickup: 100,
    homeData: {
      shopVo: {}
    },
    orderMenus: [
      { name: '全部订单', icon: 'allOrders', src: '/pages/all-order-list/index' },
      { name: '今日待揽收', icon: 'lanshou', src: '/pages/collection-products/index' },
      { name: '待提货订单', icon: 'van', src: '/pages/waiting-for-pickup-list/index' },
      { name: '售后', icon: 'after-sales', src: '/pages/sell-order-list/index' },
    ],
    servicesMenus: [
      { name: '我的账单', icon: 'my-bill', src: '/pages/bill/index' },
      { name: '销量比拼', icon: 'sales', src: '/pages/sales-volume/index' },
      { name: '快捷报单', icon: 'baodan', src: '/pages/baodan/index' },
      { name: '图文提取', icon: 'img-extract', src: '/pages/graphic-recognition/index' },
      { name: '查看会员', icon: 'vip', src: '/pages/vip/index' },
      { name: '门店录入', icon: 'addShops', src: '/pages/add-store/index' },
    ],
    withdrawEnable: false
  },
  onLoad: function (options) {
    this.getHomeData()
  },
  getHomeData: function () {
    const userInfo = userUtils.getUserInfo()
    const isLogin = userInfo && userInfo.login
    getHomeData().then(res => {
      userUtils.updateUserInfo({ shopVo: res.data.shopVo })
      let homeData = {}
      if (res.data.fakePage && !isLogin) {
        homeData = { ...res.data, ...defaultHomeData }
      } else {
        homeData = res.data
      }
      this.setData({
        homeData,
        isLogin,
      }, this.checkWithdrawEnable)
    })
  },
  checkWithdrawEnable: function () {
    const { homeData } = this.data
    const withdrawEnable = homeData.totalAmount >= this.data.minPickup
    this.setData({
      withdrawEnable
    })
  },
  editBusinessTime: function () {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({ url: '/pages/login/index' })
    } else {
      wx.navigateTo({ url: '/pages/timeRangeSelect/index' })
    }
  },
  goWidthdraw: function () {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({ url: '/pages/login/index' })
    } else {
      const { homeData } = this.data
      if (!this.data.withdrawEnable) return
      wx.navigateTo({ url: `/pages/withdraw/index?total=${homeData.totalAmount}&bankCardNo=${homeData.shopVo.bankCardNo}` })
    }
  },
  updateTimeRange: function ({ start, end }) {
    const businessTime = `${start} ~ ${end}`
    updateBusinessTime({ businessTime }).then((res) => {
      common.showToast("更新成功！")
      this.getHomeData()
    }).catch((err) => {
      common.log(err)
    })
  },
  logout: function () {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({ url: '/pages/login/index' })
    } else {
      userUtils.removeToken()
      userUtils.updateUserInfo({ login: false })
      wx.navigateTo({ url: '/pages/login/index' })
    }
  },
  goDetial: function (e) {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({ url: '/pages/login/index' })
    } else {
      const { src } = e.currentTarget.dataset;
      wx.navigateTo({ url: src })
    }
  },
  //保存到相册
  saveToAlbum: function () {
    if (this.data.homeData.fakePage && !this.data.isLogin) {
      wx.navigateTo({ url: '/pages/login/index' })
      return
    }
    const codeUrl = this.data.homeData.shopVo.codeUrl
    if (!codeUrl) {
      common.showToast("该门店没有分享码～")
      return
    }
    common.wxDownloadFile(codeUrl).then((filePath) => {
      if (wx.saveImageToPhotosAlbum) {
        wx.getSetting({
          success: res => {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              //2.提前授权
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success: res => {
                  //直接保存
                  this.savePageImageToPhotosAlbum(filePath);
                },
                fail: res => {
                  //拒绝授权,打开设置
                  this.openPhotosAlbumSetting(res, filePath);
                }
              })
            } else {
              //3.写入相册
              this.savePageImageToPhotosAlbum(filePath);
            }
          }
        })
      } else {
        common.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
      }
    })
  },

  //提示打开相册权限
  openPhotosAlbumSetting: function (res, filePath) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common.showModal("亲，我们未获得您的相册授权，即将打开设置", {
      title: '',
      showCancel: true,
    }, () => {
      wx.openSetting({
        success: response => {
          var isOpenWriteAuth = response.authSetting['scope.writePhotosAlbum'];
          if (isOpenWriteAuth) {
            this.savePageImageToPhotosAlbum(filePath);
          }
        }
      })
    })
  },
  //保存图片到相册
  savePageImageToPhotosAlbum: function (filePath) {
    wx.saveImageToPhotosAlbum({
      filePath,
      success: res => {
        common.showToast("保存成功！");
      }
    });
  },
})
